package com.csu.csumall.controller.frontend;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.csu.csumall.VO.CartVO;
import com.csu.csumall.common.CartStatus;
import com.csu.csumall.common.ItemStatus;
import com.csu.csumall.common.UniformResponse;
import com.csu.csumall.entity.Cart;
import com.csu.csumall.entity.User;
import com.csu.csumall.service.ICartService;
import com.csu.csumall.service.ICartVOService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static com.csu.csumall.common.Constant.ORIGIN;

@Slf4j
@RestController
@RequestMapping("/api/cart")
@CrossOrigin(origins = ORIGIN)
public class CartController {

    private final ICartService cartService;
    private final ICartVOService cartVOService;

    @Autowired
    public CartController(ICartService cartService, ICartVOService cartVOService) {
        this.cartService = cartService;
        this.cartVOService = cartVOService;
    }

    @GetMapping(produces = "application/json")
    public ResponseEntity<UniformResponse<Object>> get(@AuthenticationPrincipal User user) {
        return new ResponseEntity<>(
                UniformResponse.createForSuccess(cartVOService.listByUserId(user.getId())), HttpStatus.OK
        );
    }

    @GetMapping(value = "checked", produces = "application/json")
    public ResponseEntity<UniformResponse<List<CartVO>>> getCheckedList(@AuthenticationPrincipal User user) {
        List<CartVO> cartVOList = cartVOService.listChecked(user.getId());
        return new ResponseEntity<>(
                UniformResponse.createForSuccess(cartVOList),
                HttpStatus.OK
        );
    }

    @PostMapping(consumes = "application/json", produces = "application/json")
    public ResponseEntity<UniformResponse<Cart>> post(@AuthenticationPrincipal User user,
                                                      @RequestBody Cart cart) {
        cart.setUserId(user.getId());
        if (null == cart.getChecked()) {
            cart.setChecked(CartStatus.UNCHECKED.getValue());
        }
        boolean flag = cartService.addRecord(cart);
        if (flag) {
            return new ResponseEntity<>(UniformResponse.createForSuccess(cart), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(UniformResponse.createForError("创建失败"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping(consumes = "application/json", produces = "application/json")
    public ResponseEntity<UniformResponse<Cart>> put(@AuthenticationPrincipal User user,
                                                    @RequestBody(required = true) Cart cart) {
        if (null == user) {
            return new ResponseEntity<>(UniformResponse.createForForceLogin("未登录"), HttpStatus.UNAUTHORIZED);
        } else if (null == cart.getId()){
            return new ResponseEntity<>(UniformResponse.createForError("信息不足"), HttpStatus.BAD_REQUEST);
        } else {
            boolean flag = cartService.updateById(cart);
            if (flag) {
                return new ResponseEntity<>(UniformResponse.createForSuccess(cart), HttpStatus.RESET_CONTENT);
            } else {
                return new ResponseEntity<>(UniformResponse.createForError("更新失败"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    }

    @DeleteMapping(value = "{id}", produces = "application/json")
    public ResponseEntity<UniformResponse<Object>> delete(@AuthenticationPrincipal User user,
                                                          @PathVariable("id") Integer id) {
            Cart cart = new Cart();
            cart.setStatus(ItemStatus.DISABLE.getValue());
            boolean flag = cartService.update(
                    cart,
                    new QueryWrapper<Cart>().eq("product_id", id).eq("user_id", user.getId())
            );
            if (flag) {
                return new ResponseEntity<UniformResponse<Object>>(UniformResponse.createForSuccess(cart), HttpStatus.OK);
            } else {
                return new ResponseEntity<UniformResponse<Object>>(UniformResponse.createForError("删除失败"), HttpStatus.INTERNAL_SERVER_ERROR);
            }

    }

    @PatchMapping(value = "checkAll", produces = "application/json")
    public ResponseEntity<UniformResponse<Integer>> checkAll (@AuthenticationPrincipal User user) {
        if (null == user || null == user.getId()) {
            return new ResponseEntity<>(UniformResponse.createForError("未登录"), HttpStatus.UNAUTHORIZED);
        }
        Integer count = cartService.checkAll(user.getId());
        return new ResponseEntity<>(UniformResponse.createForSuccess(count), HttpStatus.CREATED);
    }

    @PatchMapping(value = "unCheckAll", produces = "application/json")
    public ResponseEntity<UniformResponse<Integer>> unCheckAll (@AuthenticationPrincipal User user) {
        if (null == user || null == user.getId()) {
            return new ResponseEntity<>(UniformResponse.createForError("未登录"), HttpStatus.UNAUTHORIZED);
        }
        Integer count = cartService.unCheckAll(user.getId());
        return new ResponseEntity<>(UniformResponse.createForSuccess(count), HttpStatus.CREATED);
    }


    @PatchMapping(value = "{id}", produces = "application/json")
    public ResponseEntity<UniformResponse<Object>> patchOneItem (
                                        @AuthenticationPrincipal User user,
                                        @PathVariable(value = "id") Integer id,
                                        @RequestParam(value = "action") String action,
                                        @RequestParam(value = "quantity", required = false) Integer quantity
    ) {
        Cart cart = cartService.getOne(
                new QueryWrapper<Cart>().eq("product_id", id).eq("user_id", user.getId())
        );
        switch (action) {
            case "updateNum":
                if (null == quantity) {
                    return new ResponseEntity<>(UniformResponse.createForError("未传入quantity"), HttpStatus.BAD_REQUEST);
                } else {
                    cart.setQuantity(quantity);
                }
                break;
            case "check":
                cart.setChecked(CartStatus.CHECKED.getValue());
                break;
            case "uncheck":
                cart.setChecked(CartStatus.UNCHECKED.getValue());
                break;
            default:
                return new ResponseEntity<>(UniformResponse.createForError("未传入quantity"), HttpStatus.BAD_REQUEST);
        }

        boolean flag = cartService.updateById(cart);
        if (flag) {
            return new ResponseEntity<>(UniformResponse.createForSuccess("OK"), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(UniformResponse.createForError("ERROR"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping(value = "totalPrice", produces = "application/json")
    public ResponseEntity<UniformResponse<AtomicInteger>> totalPrice (@AuthenticationPrincipal User user) {
        Integer userId = user.getId();
        List<CartVO> cartVOList = cartVOService.listByUserId(userId);
        AtomicInteger totalPrice = new AtomicInteger(0);
        cartVOList.forEach(cartVO -> {
            totalPrice.addAndGet(CartStatus.CHECKED.getValue() == cartVO.getChecked() ? cartVO.getQuantity() * cartVO.getPrice() : 0);
        });
        return new ResponseEntity<>(UniformResponse.createForSuccess(totalPrice), HttpStatus.OK);
    }

    @GetMapping(value = "price/{id}", produces = "application/json")
    public ResponseEntity<UniformResponse<Integer>> itemTotalPrice (@AuthenticationPrincipal User user,
                                                             @PathVariable("id") Integer id) {
        CartVO cartVO = cartVOService.getOne(user.getId(), id);
        Integer price = cartVO.getQuantity() * cartVO.getPrice();
        log.info(String.valueOf(price));
        return new ResponseEntity<UniformResponse<Integer>>(UniformResponse.createForSuccess(price), HttpStatus.OK);
    }




}
